package com.fileupload.process.strategy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * 基于相对路径的移动策略
 * 上传完成后按照原文件的相对路径结构移动到目标位置
 * @author 小乙
 */
public class RelativePathMoveFileStrategy extends AbstractFileFinishActionStrategy {
    
    private static final Logger logger = LoggerFactory.getLogger(RelativePathMoveFileStrategy.class);
    
    /**
     * 默认构造函数
     */
    public RelativePathMoveFileStrategy() {
        super("relative-path");
    }
    
    /**
     * 构造函数
     * 
     * @param monitorDir 监控目录
     */
    public RelativePathMoveFileStrategy(String monitorDir) {
        super("relative-path", monitorDir);
    }
    
    @Override
    public boolean execute(File sourceFile, String targetDir) {
        logger.debug("执行基于相对路径的移动操作: 文件={}, 目标目录={}, 监控目录={}", 
                   sourceFile.getAbsolutePath(), targetDir, getMonitorDir());
        
        if (sourceFile == null || !sourceFile.exists() || targetDir == null || targetDir.isEmpty()) {
            logger.warn("Invalid parameters for moving file");
            return false;
        }
        
        try {
            // 获取相对路径
            String relativePath = getRelativePath(sourceFile, getMonitorDir());
            
            // 构建目标目录路径
            String targetPath = targetDir.endsWith("/") ? targetDir : targetDir + "/";
            if (!relativePath.isEmpty()) {
                targetPath += relativePath.startsWith("/") ? relativePath.substring(1) : relativePath;
            }
            
            // 创建目标目录
            boolean dirCreated = createDirectory(targetPath);
            if (!dirCreated) {
                return false;
            }
            
            // 移动文件到目标目录
            Path targetFilePath = Paths.get(targetPath, sourceFile.getName());
            Files.move(sourceFile.toPath(), targetFilePath, StandardCopyOption.REPLACE_EXISTING);
            
            logger.info("File moved with relative path: {} -> {}", 
                       sourceFile.getAbsolutePath(), targetFilePath.toString());
            return true;
            
        } catch (IOException e) {
            logger.error("Failed to move file with relative path: {}", sourceFile.getAbsolutePath(), e);
            return false;
        }
    }
}
